/**
 * 
 */
package com.comunity_cloud.rest;

import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

/**
 *
 */
@SuppressWarnings("deprecation")
public class HttpClientFactory {

	private static DefaultHttpClient client;

	public synchronized static DefaultHttpClient getThreadSafeClient() {

		if (client != null)
			return client;

		// HTTP parameters
		
		
		
		
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		// http scheme
		schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 8080));
		// https scheme
		schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

		HttpParams params = new BasicHttpParams();
		params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
		params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
		params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
		params.setBooleanParameter("http.protocol.expect-continue", false);
		ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
		client = new DefaultHttpClient(cm, params);
		
//		This doesn't work because we remove WWW-Authenticate header
//		client.getCredentialsProvider().setCredentials(
//				new AuthScope("rushphone.ru", 443,"rushphone-web"),
//				new UsernamePasswordCredentials(RestClient.cachedPassword, RestClient.cachedUserName));
		    
		// TODO - newer library code. Android has older version
		//ThreadSafeClientConnManager(params, registry) was reported as deprecated with 4.1.1
//		ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager();
//		connManager.setDefaultMaxPerRoute(20);
//		connManager.setMaxTotal(20);
//		client = new DefaultHttpClient(connManager);
	
		
		
		return client;
		
	}

	public static void shutdown() {
		client = null;
	} 
}
